"""
应用配置模块
"""

import os
from pathlib import Path
from datetime import timedelta


class Config:
    """基础配置类"""
    
    # Flask基础配置
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'dev-secret-key-change-in-production'
    DEBUG = os.environ.get('FLASK_DEBUG', 'False').lower() == 'true'
    TESTING = False
    
    # 服务器配置
    HOST = os.environ.get('FLASK_HOST', '0.0.0.0')
    PORT = int(os.environ.get('FLASK_PORT', 5000))
    
    # 数据库配置
    MONGO_URI = os.environ.get('MONGO_URI', 'mongodb://localhost:27017/md2dockit')
    REDIS_URL = os.environ.get('REDIS_URL', 'redis://localhost:6379/0')
    
    # 文件存储配置
    BASE_DIR = Path(__file__).parent.parent.parent
    STORAGE_DIR = BASE_DIR / 'storage'
    UPLOAD_FOLDER = str(STORAGE_DIR / 'uploads')
    OUTPUT_FOLDER = str(STORAGE_DIR / 'outputs')
    TEMP_FOLDER = str(STORAGE_DIR / 'temp')
    
    # 文件上传限制
    MAX_CONTENT_LENGTH = int(os.environ.get('MAX_FILE_SIZE', 16 * 1024 * 1024))  # 16MB
    ALLOWED_EXTENSIONS = {
        'md', 'markdown', 'txt', 'rst', 'org', 'textile', 'creole',
        'mediawiki', 'vimwiki', 'asciidoc', 'html', 'htm'
    }
    
    # 输出格式配置
    SUPPORTED_OUTPUT_FORMATS = {
        'docx', 'pdf', 'html', 'epub', 'odt', 'rtf', 'tex', 'pptx'
    }
    
    # Pandoc配置
    PANDOC_PATH = os.environ.get('PANDOC_PATH', 'pandoc')
    PANDOC_DATA_DIR = os.environ.get('PANDOC_DATA_DIR', '')
    
    # WeasyPrint配置
    WEASYPRINT_DPI = int(os.environ.get('WEASYPRINT_DPI', 96))
    WEASYPRINT_OPTIMIZE_SIZE = os.environ.get('WEASYPRINT_OPTIMIZE_SIZE', 'True').lower() == 'true'
    
    # Celery配置
    CELERY_BROKER_URL = os.environ.get('CELERY_BROKER_URL', 'redis://localhost:6379/0')
    CELERY_RESULT_BACKEND = os.environ.get('CELERY_RESULT_BACKEND', 'redis://localhost:6379/0')
    CELERY_TASK_SERIALIZER = 'json'
    CELERY_RESULT_SERIALIZER = 'json'
    CELERY_ACCEPT_CONTENT = ['json']
    CELERY_TIMEZONE = 'UTC'
    CELERY_ENABLE_UTC = True
    
    # 任务配置
    TASK_TIMEOUT = int(os.environ.get('TASK_TIMEOUT', 300))  # 5分钟
    MAX_CONCURRENT_TASKS = int(os.environ.get('MAX_CONCURRENT_TASKS', 5))
    TASK_RETRY_DELAY = int(os.environ.get('TASK_RETRY_DELAY', 60))  # 1分钟
    MAX_TASK_RETRIES = int(os.environ.get('MAX_TASK_RETRIES', 3))
    
    # 文件清理配置
    FILE_RETENTION_HOURS = int(os.environ.get('FILE_RETENTION_HOURS', 24))  # 24小时
    CLEANUP_INTERVAL_HOURS = int(os.environ.get('CLEANUP_INTERVAL_HOURS', 6))  # 6小时
    
    # 安全配置
    CORS_ORIGINS = os.environ.get('CORS_ORIGINS', 'http://localhost:5173').split(',')
    RATE_LIMIT_ENABLED = os.environ.get('RATE_LIMIT_ENABLED', 'True').lower() == 'true'
    RATE_LIMIT_DEFAULT = os.environ.get('RATE_LIMIT_DEFAULT', '100 per hour')
    
    # 日志配置
    LOG_LEVEL = os.environ.get('LOG_LEVEL', 'INFO')
    LOG_FILE = os.environ.get('LOG_FILE', 'logs/app.log')
    LOG_MAX_BYTES = int(os.environ.get('LOG_MAX_BYTES', 10 * 1024 * 1024))  # 10MB
    LOG_BACKUP_COUNT = int(os.environ.get('LOG_BACKUP_COUNT', 5))
    
    # WebSocket配置
    SOCKETIO_ASYNC_MODE = os.environ.get('SOCKETIO_ASYNC_MODE', 'threading')
    SOCKETIO_LOGGER = os.environ.get('SOCKETIO_LOGGER', 'False').lower() == 'true'
    SOCKETIO_ENGINEIO_LOGGER = os.environ.get('SOCKETIO_ENGINEIO_LOGGER', 'False').lower() == 'true'
    
    # 模板配置
    TEMPLATE_DIR = BASE_DIR / 'templates'
    CSS_THEMES_DIR = BASE_DIR / 'themes'
    DEFAULT_TEMPLATE = os.environ.get('DEFAULT_TEMPLATE', 'default')
    DEFAULT_CSS_THEME = os.environ.get('DEFAULT_CSS_THEME', 'github')
    
    # 质量评估配置
    QUALITY_CHECK_ENABLED = os.environ.get('QUALITY_CHECK_ENABLED', 'True').lower() == 'true'
    MIN_QUALITY_SCORE = int(os.environ.get('MIN_QUALITY_SCORE', 70))
    
    # 监控配置
    HEALTH_CHECK_ENABLED = os.environ.get('HEALTH_CHECK_ENABLED', 'True').lower() == 'true'
    METRICS_ENABLED = os.environ.get('METRICS_ENABLED', 'False').lower() == 'true'
    
    # 邮件配置（可选）
    MAIL_SERVER = os.environ.get('MAIL_SERVER')
    MAIL_PORT = int(os.environ.get('MAIL_PORT', 587))
    MAIL_USE_TLS = os.environ.get('MAIL_USE_TLS', 'True').lower() == 'true'
    MAIL_USERNAME = os.environ.get('MAIL_USERNAME')
    MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD')
    MAIL_DEFAULT_SENDER = os.environ.get('MAIL_DEFAULT_SENDER')
    
    @staticmethod
    def init_app(app):
        """初始化应用配置"""
        pass


class DevelopmentConfig(Config):
    """开发环境配置"""
    DEBUG = True
    LOG_LEVEL = 'DEBUG'
    SOCKETIO_LOGGER = True
    SOCKETIO_ENGINEIO_LOGGER = True


class ProductionConfig(Config):
    """生产环境配置"""
    DEBUG = False
    LOG_LEVEL = 'INFO'
    RATE_LIMIT_ENABLED = True
    
    @staticmethod
    def init_app(app):
        Config.init_app(app)
        
        # 生产环境特定配置
        import logging
        from logging.handlers import RotatingFileHandler
        
        # 配置文件日志
        if not app.debug and not app.testing:
            if not os.path.exists('logs'):
                os.mkdir('logs')
            
            file_handler = RotatingFileHandler(
                'logs/md2dockit.log',
                maxBytes=Config.LOG_MAX_BYTES,
                backupCount=Config.LOG_BACKUP_COUNT
            )
            file_handler.setFormatter(logging.Formatter(
                '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
            ))
            file_handler.setLevel(logging.INFO)
            app.logger.addHandler(file_handler)
            
            app.logger.setLevel(logging.INFO)
            app.logger.info('MD2DocKit startup')


class TestingConfig(Config):
    """测试环境配置"""
    TESTING = True
    DEBUG = True
    MONGO_URI = 'mongodb://localhost:27017/md2dockit_test'
    REDIS_URL = 'redis://localhost:6379/1'
    WTF_CSRF_ENABLED = False
    RATE_LIMIT_ENABLED = False
    FILE_RETENTION_HOURS = 1  # 测试环境文件保留1小时
    CELERY_TASK_ALWAYS_EAGER = True  # 同步执行任务


# 配置字典
config = {
    'development': DevelopmentConfig,
    'production': ProductionConfig,
    'testing': TestingConfig,
    'default': DevelopmentConfig
}